package com.hyjx.framework.component.fastdfs;

import com.hyjx.framework.common.CommonUtil;
import com.hyjx.framework.common.util.StringHelper;
import com.hyjx.framework.component.upload.UploadModel;
import com.hyjx.framework.component.upload.UploadService;
import com.hyjx.framework.orm.dao.IBaseDao;
import com.hyjx.framework.service.ConfigManager;
import com.hyjx.framework.service.UserCenterService;
import com.hyjx.framework.uc.user.UserInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Iterator;

/**
 * 附件接口的分步式实现类
 */
@Service("fastDFSService")
@Transactional
public class FastDFSServiceImpl implements UploadService {
    
    @Resource
    private IBaseDao dao;
    
    public void setDao(IBaseDao dao) {
        this.dao = dao;
    }

    @Override
    public String queryList(Object model) {
        UploadModel um = (UploadModel) model;

        FastDFSModel fastDFSModel = new FastDFSModel();
        return dao.getPageJsonStr(fastDFSModel.getModuleName() + ".getfilebyuploadmodel", fastDFSModel.getModuleName() + ".getfilebyuploadmodelNum", um);
    }

    @Override
    public boolean add(MultipartHttpServletRequest request,
                       HttpServletResponse response) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html");
            String businessId = request.getParameter("vchr_entityid") == null ? "" : request.getParameter("vchr_entityid");
            String vchr_domain = request.getParameter("vchr_domain") == null ? "" : request.getParameter("vchr_domain");
            String fileType = request.getParameter("fileType") == null ? "" : request.getParameter("fileType");
            Iterator<String> iterator = request.getFileNames();
            while (iterator.hasNext()) {
                String fileName = iterator.next();
                MultipartFile multipartFile = request.getFile(fileName);
                FastDFSModel fastdfsModel = new FastDFSModel();
                //获取用户信息 此处注掉
                UserInfo userinfo = UserCenterService.getCurrentUserInfo();
                // 原图
                byte[] file_buff = multipartFile.getBytes();
                //图片后缀
                String etx = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().indexOf(".") + 1);
                FastDFSFile fdfsFile = new FastDFSFile(multipartFile.getName(), file_buff, etx);
                // 中号缩略图
                byte[] file_buff2 = ImageHelp.resizeImg(multipartFile.getInputStream(), 0.7, etx);
                FastDFSFile fdfsFile2 = new FastDFSFile(multipartFile.getName(), file_buff, multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().indexOf(".") + 1));
                // 小缩略图
                byte[] file_buff3 = ImageHelp.resizeImg(multipartFile.getInputStream(), 0.3, etx);
                //保存原图
                FileManager manager = new FileManager();
                String fileAbsolutePath = manager.upload(fdfsFile);
                //保存中号缩略图
                fdfsFile.setContent(file_buff2);
                String fileAbsolutePath2 = manager.upload(fdfsFile);
                //保存小缩略图
                fdfsFile.setContent(file_buff3);
                String fileAbsolutePath3 = manager.upload(fdfsFile);
                //主键id
                String Fid = CommonUtil.getUUID32();
                fastdfsModel.setId(Fid);
                fastdfsModel.setFile_size(String.valueOf(multipartFile.getSize()));
                String fileName2 = multipartFile.getOriginalFilename();
                if (fileName2.length() > 100) {
                    fileName2 = fileName2.substring(fileName2.length() - 100);
                }
                fastdfsModel.setFile_name(fileName2);
                fastdfsModel.setFile_type(multipartFile.getContentType());
                String upload_time = StringHelper.getDateTime();
                fastdfsModel.setUpload_time(upload_time);
                //取上传的用户名称
                fastdfsModel.setUploader(userinfo.getUser_name());

                //原图
                fastdfsModel.setUploader(userinfo.getUser_name());
                String fdfs_path = fileAbsolutePath.split("/", 6)[5];
                String group_name = fileAbsolutePath.split("/", 6)[4];
                fastdfsModel.setFdfs_path(fdfs_path);
                fastdfsModel.setGroup_name(group_name);
                String[] items = fileAbsolutePath.split("/", 7);
                String visit_url = items[0] + "//" + items[2] + ":" + items[3] + "/" + items[6];

                fastdfsModel.setVisit_url(visit_url);
                fastdfsModel.setBusiness_id(businessId);
                dao.addObject(fastdfsModel.getModuleName() + ".insert", fastdfsModel);

                if ("1".equals(request.getParameter("osmFlag")) && "1".equals(fileType)) {
                    //插入中号缩略图
                    fastdfsModel.setId(Fid + "-m");
                    fastdfsModel.setFile_size(String.valueOf(file_buff2.length));
                    fdfs_path = fileAbsolutePath2.split("/", 6)[5];
                    group_name = fileAbsolutePath2.split("/", 6)[4];
                    fastdfsModel.setFdfs_path(fdfs_path);
                    fastdfsModel.setGroup_name(group_name);
                    items = fileAbsolutePath2.split("/", 7);
                    visit_url = items[0] + "//" + items[2] + ":" + items[3] + "/" + items[6];
                    fastdfsModel.setVisit_url(visit_url);
                    fastdfsModel.setBusiness_id(businessId + "-m");
                    dao.addObject(fastdfsModel.getModuleName() + "insert", fastdfsModel);

                    //插入小号缩略图
                    fastdfsModel.setId(Fid + "-s");
                    fastdfsModel.setFile_size(String.valueOf(file_buff3.length));
                    fdfs_path = fileAbsolutePath3.split("/", 6)[5];
                    group_name = fileAbsolutePath3.split("/", 6)[4];
                    fastdfsModel.setFdfs_path(fdfs_path);
                    fastdfsModel.setGroup_name(group_name);
                    items = fileAbsolutePath3.split("/", 7);
                    visit_url = items[0] + "//" + items[2] + ":" + items[3] + "/" + items[6];
                    fastdfsModel.setVisit_url(visit_url);
                    fastdfsModel.setBusiness_id(businessId + "-s");
                    dao.addObject(fastdfsModel.getModuleName() + ".insert", fastdfsModel);
                }
                response.getWriter().print(File.separator + Fid + File.separator + Fid + File.separator + Fid);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Object getInfoById(String s) {
        UploadModel model = (UploadModel) dao.queryObject((new FastDFSModel()).getModuleName() + ".getFileUploadModelById", s);
        return model;
    }

    @Override
    public int delete(String ids) {
    
        FastDFSModel fastdfsModel1 = new FastDFSModel();
        int result = 0;
        try {
            FastDFSModel fastdfsModel = (FastDFSModel) dao.queryObject(fastdfsModel1.getModuleName() + ".getFileById", ids);
            String groupName = fastdfsModel.getGroup_name();
            String remoteFileName = fastdfsModel.getFdfs_path();
            FileManager manager = new FileManager();
            manager.deleteFile(groupName, remoteFileName);
            result = dao.deleteObject(fastdfsModel1.getModuleName() + ".delete", ids);
        } catch (Exception e) {
            e.printStackTrace();
            
        }
        return result;
    }

    @Override
    public UploadModel getUploadModelByStorageName(String storageName) {
        return null;
    }

    @Override
    public String download(HttpServletRequest request,
                           HttpServletResponse response) {

        String ids = request.getParameter("id");
        FastDFSModel fastdfsModel = (FastDFSModel) dao.queryObject((new FastDFSModel()).getModuleName() + ".getFileById", ids);

        ServletOutputStream sos = null;
        try {
            /*URL url = new URL(model.getVisit_url());
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			InputStream is = conn.getInputStream();*/
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "filename=" + new String(fastdfsModel.getFile_name().getBytes(), "ISO8859-1"));
            sos = response.getOutputStream();
			/*byte[] isb = new byte[1024];
			int i = 0;
			while ((i = is.read(isb)) > 0) {
				sos.write(isb, 0, i);
			}*/

            String groupName = fastdfsModel.getGroup_name();
            String remoteFileName = fastdfsModel.getFdfs_path();
            FileManager manager = new FileManager();
            byte[] aa = manager.download(groupName, remoteFileName);
            sos.write(aa);
            sos.flush();
            response.flushBuffer();
            sos.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (sos != null) {
                try {
                    sos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }

    @Override
    public String view(HttpServletRequest request,
                       HttpServletResponse response) {

        String ids = request.getParameter("id");
        FastDFSModel fastdfsModel = (FastDFSModel) dao.queryObject((new FastDFSModel()).getModuleName() + ".getFileById", ids);

        ServletOutputStream sos = null;
        try {
			/*URL url = new URL(model.getVisit_url());
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			InputStream is = conn.getInputStream();*/
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fastdfsModel.getFile_name().getBytes(), "ISO8859-1"));
            sos = response.getOutputStream();
			/*byte[] isb = new byte[1024];
			int i = 0;
			while ((i = is.read(isb)) > 0) {
				sos.write(isb, 0, i);
			}*/

            String groupName = fastdfsModel.getGroup_name();
            String remoteFileName = fastdfsModel.getFdfs_path();
            FileManager manager = new FileManager();
            byte[] aa = manager.download(groupName, remoteFileName);
            sos.write(aa);
            sos.flush();
            response.flushBuffer();
            sos.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (sos != null) {
                try {
                    sos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }

    @Override
    public void getIcon(String cateogry, HttpServletRequest request,
                        HttpServletResponse response) {
        try {
            String fileName = request.getParameter("fileName");
            ServletOutputStream sos = null;
            FastDFSModel fastdfsModel = (FastDFSModel) dao.queryObject((new FastDFSModel()).getModuleName() + ".getFileById", fileName);
            if (fastdfsModel != null) {
                String groupName = fastdfsModel.getGroup_name();
                String remoteFileName = fastdfsModel.getFdfs_path();
                FileManager manager = new FileManager();
                byte[] aa = manager.download(groupName, remoteFileName);
                sos = response.getOutputStream();
                if (aa == null || aa.length == 0) {

                    File file = new File(request.getSession().getServletContext().getRealPath("/") + "component/images/noPic.jpg");
                    FileInputStream inputStream = new FileInputStream(file);
                    aa = new byte[(int) file.length()];
                    int length = inputStream.read(aa);
                }
                sos.write(aa);
                //FastDFSModel model = (FastDFSModel) this.getInfoById(vchr_id);

                //String tracker_http_addr="";
                //String tracker_http_port="84";
			/*	URL url = new URL(model.getVisit_url());
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				InputStream is = conn.getInputStream();
				response.setCharacterEncoding("utf-8");
				response.setContentType("image/png");
				sos = response.getOutputStream();
				byte[] isb = new byte[1024];
				int i = 0;
				while ((i = is.read(isb)) > 0) {
					sos.write(isb, 0, i);
					
				}*/


                sos.flush();
                response.flushBuffer();
                sos.close();
            } else {
                File file = new File(request.getSession().getServletContext().getRealPath("/") + "component/images/noPic.jpg");
				/*// 判断文件是否存在如果不存在就返回默认图标
				if (!(file.exists() && file.canRead())) {
					file = new File(request.getSession().getServletContext().getRealPath("/") + "resource/icons/auth/root.png");
				}*/
                FileInputStream inputStream = new FileInputStream(file);
                byte[] data = new byte[(int) file.length()];
                int length = inputStream.read(data);
                inputStream.close();
                response.setContentType("image/png");
                OutputStream stream = response.getOutputStream();
                stream.write(data);
                stream.flush();
                stream.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String queryCurrentPics(HttpServletRequest request) {
        String vchr_entityid = request.getParameter("vchr_entityid");
        String vchr_domain = request.getParameter("vchr_domain");
        UploadModel model = new UploadModel();
        model.setVchr_domain(vchr_domain);
        model.setVchr_entityid(vchr_entityid);
        return this.queryList(model);

    }

    @Override
    public void addCapture(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String outMessage = "";
        String picdata = request.getParameter("picdata");
        String vchr_entityid = request.getParameter("vchr_entityid");
        String vchr_domain = request.getParameter("vchr_domain");
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] picbyte = decoder.decodeBuffer(picdata);
        //String fileName = UUID.randomUUID().toString()+"upload_pic.jpg";
        String fileName = System.currentTimeMillis() + ".jpg";
        String upPath = ConfigManager.getAttatchmentsPicPath() + File.separator + vchr_domain + File.separator + vchr_entityid + File.separator;
        File upload = new File(upPath);
        if (!upload.exists()) {
            upload.mkdirs();
        }
		/*UploadModel model = new UploadModel();
		model.setVchr_id(StringHelper.getPrimaryKey());
		model.setDate_uploaddate(StringHelper.getDateTime());
		model.setLastdate(StringHelper.getDateTime());
		model.setNum_filesize("100");
		model.setVchr_entityid(vchr_entityid);
		model.setVchr_domain(vchr_domain);
		model.setVchr_originname(fileName);
		model.setVchr_storagename(fileName);*/

        //byte[] file_buff = multipartFile.getBytes();
        FastDFSFile fdfsFile = new FastDFSFile(fileName, picbyte, fileName.substring(fileName.indexOf(".") + 1));
        FileManager manager = new FileManager();
        String fileAbsolutePath = manager.upload(fdfsFile);

        FastDFSModel fastdfsModel = new FastDFSModel();
        UserInfo userinfo = UserCenterService.getCurrentUserInfo();
        fastdfsModel.setId(CommonUtil.getUUID32());
        fastdfsModel.setFile_size(String.valueOf(picbyte.length));
        fastdfsModel.setFile_name(fileName);
        fastdfsModel.setFile_type("image/jpeg");
        String upload_time = StringHelper.getDateTime();
        fastdfsModel.setUpload_time(upload_time);
        fastdfsModel.setUploader(userinfo.getUser_name());
        String fdfs_path = fileAbsolutePath.split("/", 6)[5];
        String group_name = fileAbsolutePath.split("/", 6)[4];
        fastdfsModel.setFdfs_path(fdfs_path);
        fastdfsModel.setGroup_name(group_name);
        String[] items = fileAbsolutePath.split("/", 7);
        String visit_url = items[0] + "//" + items[2] + "/" + items[6];
        fastdfsModel.setVisit_url(visit_url);
        fastdfsModel.setBusiness_id(vchr_entityid);
        dao.addObject(fastdfsModel.getModuleName() + "insert", fastdfsModel);
        FileOutputStream fos = new FileOutputStream(upPath + File.separator + fileName);
        try {
            fos.write(picbyte);
            fos.flush();
            fos.close();
            outMessage = "{\"code\":0,\"info\":\"" + fileName + "\"}";
        } catch (IOException e) {
            e.printStackTrace();
            outMessage = "{\"code\":1,\"message\":\"" + e.toString() + "\"}";

        }
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.getOutputStream().write(outMessage.getBytes("utf-8"));
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }
}